<!DOCTYPE HTML>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script src="../../../resources/gesture-util.js"></script>
<script src="../../../virtual/percent-based-scrolling/resources/percent-based-util.js"></script>
<style>
#targetDiv {
  width: 200px;
  height: 200px;
  overflow: scroll;
}

#innerDiv {
  width: 400px;
  height: 400px;
}
</style>

<body style="margin:0">
<div id="targetDiv">
  <div id="innerDiv">
  </div>
</div>
</body>

<script>
if (window.internals)
  internals.runtimeFlags.overscrollCustomizationEnabled = true;

var target_div = document.getElementById('targetDiv');
var rect = target_div.getBoundingClientRect();
var x = rect.left + rect.width / 2;
var y = rect.top + rect.height / 2;

const pixelsToScroll = 800;
const { y: pixelsToScrollY } = calculatePixelsToScroll(
  target_div, pixelsToScroll, pixelsToScroll
);

async function test_scrollend_event_fire(t, source_device,
                                         precise_scrolling_delta) {
  scrollend_arrived = false;
  await waitForCompositorCommit();

  // Make sure that no scrollend event is sent to target_div.
  const listener = target_div.addEventListener("scrollend",
      t.unreached_func("target_div got unexpected scrollend event."));
  t.add_cleanup(() => target_div.removeEventListener('scrollend', listener));

  // Scroll up on target div and wait for the window to get the scrollend event.
  const scrollendPromise = waitForScrollendEvent(window);
  await smoothScroll(
    pixelsToScrollY, x, y, source_device, "up", SPEED_INSTANT,
    precise_scrolling_delta
  );
  await scrollendPromise.then((event) => {
    assert_false(event.cancelable);
    // scrollend events targeting the document are bubbled to the window.
    assert_true(event.bubbles);
  });
  assert_equals(target_div.scrollTop, 0);

  // Wait two additional frames to ensure that unexpected events are not
  // received.
  await raf();
  await raf();
}

promise_test (async (t) => {
  return test_scrollend_event_fire(t, GestureSourceType.TOUCH_INPUT);
}, 'Tests that the window gets scrollend event when no element scrolls ' +
   'after touch scrolling.');
promise_test (async (t) => {
  return test_scrollend_event_fire(t, GestureSourceType.MOUSE_INPUT, true);
}, 'Tests that the window gets scrollend event when no element scrolls ' +
   'after non-animated wheel scrolling.');
promise_test (async (t) => {
  return test_scrollend_event_fire(t, GestureSourceType.MOUSE_INPUT, false);
}, 'Tests that the window gets scrollend event when no element scrolls ' +
   'after animated wheel scrolling(smooth scrolling).');
</script>
